package com.zzl.study.auth.redis;

import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.NonNull;

/**
 * @author: zhangzl
 * @date: 2024/3/11 16:16
 * @version: 1.0
 * @description: Common RedisTemplate
 */
public class CommonRedisTemplate extends RedisTemplate<String, Object> {

    public CommonRedisTemplate() {
        this.initSerializer();
    }

    public CommonRedisTemplate(RedisConnectionFactory connectionFactory) {
        this();
        this.setConnectionFactory(connectionFactory);
        this.initSerializer();
        this.afterPropertiesSet();
    }

    @Override
    @NonNull
    protected RedisConnection preProcessConnection(@NonNull RedisConnection connection, boolean existingConnection) {
        return new DefaultStringRedisConnection(connection);
    }

    private void initSerializer() {
        this.setKeySerializer(keySerializer());
        this.setHashKeySerializer(keySerializer());
        this.setValueSerializer(valueSerializer());
        this.setHashValueSerializer(valueSerializer());
    }

    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }

    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }

}
